<?php
$con = mysql_connect("localhost","haschool_mdl1","B97C0HRYb7");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
$db_selected = mysql_select_db("haschool_mdl1", $con);
if (!$db_selected) {
    die ('Can\'t use haschool_mdl1 : ' . mysql_error());
}  

$salt = '>;4khn&9g9?3d]{%xuVp@gir{vwp';
$password = md5($_POST[password].$salt);
$username = $_POST[username];	
$pwd = $_POST[password];
//echo '<script language="javascript">alert("One of the username newly added already exists. Please modify the username (s) '.$username.' and try again.")</script>;';	

if((!$username or $username=='') and (!$_POST[password] or $_POST[password]=='' ))
{
	$password = $_GET[password];
	$username = $_GET[username];
	$unexist = $_GET[unexist];
	$emailexist = $_GET[emailexist];
	if ($unexist==1){
		echo '<script language="javascript">alert("One of the username newly added already exists. Please modify the username (s) and try again.")</script>;';	
	}
	if ($emailexist and $emailexist!=''){
		echo '<script language="javascript">alert("The email address: '.$emailexist.' exists already. Please set unique email address and try again.")</script>;';	
	}
}

$sqltest = 'SELECT * from mdl_user where username=\''.$username.'\' and password=\''.$password.'\'';
$result = mysql_query('SELECT * from mdl_user where username=\''.$username.'\' and password=\''.$password.'\'');
if (!$result) {
	ob_start();
	echo "Incorrect login or password";
	header( 'Location: http://haschoolmanagement.com/management/index.php?login=incorrect&query='.$sqltest ) ;
    ob_flush();
}

$userinfo = mysql_fetch_array($result);
if (!$userinfo or count($userinfo)==0) {
	ob_start();
	echo "Incorrect login or password";
	header( 'Location: http://haschoolmanagement.com/management/index.php?login=incorrect&query='.$sqltest  ) ;
    ob_flush();
}

$userid = $userinfo['id'];
$sqlroleass = 'SELECT roleid from mdl_role_assignments where userid='.$userid.' and roleid=1';
$result = mysql_query($sqlroleass);
$userrole = mysql_fetch_array($result);
if (!$userrole or count($userrole)==0) {
	ob_start();
	echo "Access denied";
	header( 'Location: http://haschoolmanagement.com/management/index.php?role=incorrect') ;
    ob_flush();
}

/******* Course list *****/
$sqlcourse = 'SELECT id, fullname from mdl_course';
$courseid=$_POST[courseid];
$currCourseName = "";
$result = mysql_query($sqlcourse);
$i=0;
While( $courses = mysql_fetch_array($result) )
  {
	$arrCourse[$i] = array ( 'courseid' 	=> $courses['id'],
							 'coursename' 	=> $courses['fullname']
						   );
	if ($courseid == $courses['id'])
	{
		$currCourseName = $courses['fullname'];
	}
	$i=$i+1;
  }

/**   Students list *****/
if ($courseid!='' and $courseid>0) 
{
	$sqlstudent = 'SELECT u.id, lastname, firstname, data from mdl_user u, mdl_user_enrolments e, mdl_user_info_data dob where e.enrolid ='.$courseid.
				' and e.userid = u.id and dob.fieldid = 1 and dob.userid = u.id  and ( e.timeend=null OR e.timeend =0 OR e.timeend > '.time().')'.
				' order by data';
	
	$result = mysql_query($sqlstudent);
	$i=0;
	While( $student = mysql_fetch_array($result) )
	  {
		$arrStudents[$i] = array (  'userid' 	=> $student['id'],
									'firstname' => $student['firstname'],
								    'lastname' 	=> $student['lastname'], 
								    'dob' 	    => $student['data'] 
								 );
		$i=$i+1;
	  }
}

/** Apply groups assignment **/
$toapply = $_POST[toapply];
$groupsizevalue = $_POST[groupsizevalue];
if ( ($toapply!='' and $toapply>0) and ($courseid!='' and $courseid>0) and count($arrStudents)>0 )
{
    /*** Get Groups ***/
	$sqlgroups = 'SELECT id, name from mdl_groups where courseid='.$courseid.' order by id';
	$result = mysql_query($sqlgroups);
	$i=0;
	While( $group = mysql_fetch_array($result) )
	  {
		$arrgroups[$i] = array ( 'id' 	=> $group['id'],
						    	 'name' => $group['name']
								 );
		/*** Cleanup Group members   ****/
		$sqlgroupsmembers = "Delete from mdl_groups_members where groupid=".$arrgroups[$i][id];
		$resultdelete = mysql_query($sqlgroupsmembers);
		$i=$i+1;
	  }
	
	/*** Assign members to groups ***/
	$stdCount = count($arrStudents);
		
	$GroupCount = $stdCount / $groupsizevalue;
	if ( $GroupCount > round($GroupCount)){
		$GroupCount = round($GroupCount) + 1 ;
	}else{
		$GroupCount = round($GroupCount);
	}
	
	$i=0;
	if (count($arrgroups)< $GroupCount)
	{
		for ($i=0; $i < ($GroupCount - count($arrgroups)); $i++)
		{
			$courseNumber = count($arrgroups) + $i + 1;
			$sqladdgroups = "INSERT INTO mdl_groups(courseid, name) VALUES (". $courseid .", '".$currCourseName."_".$courseNumber."' )";
			mysql_query($sqladdgroups);
			$idAddedCourse = mysql_insert_id();
			$arrgroupsAdj[count($arrgroups) + $i ] = array ( 'id' 	=> $idAddedCourse,
														'name'  => $currCourseName."_".$courseNumber
													);												
		}
		$arrgroups = array_merge($arrgroups, $arrgroupsAdj);
	}
	
	$g=0;
	$stdId=0;
	$j=0;
	While( $g < $GroupCount )
	  {
		$groupid = $arrgroups[$g][id];
		for ($j = $stdId; $j < $stdCount; $j++) {
			if ( $j < (($g+1)*$groupsizevalue))
			{
				$sqlassmembers = 'INSERT INTO mdl_groups_members(groupid, userid) VALUES ('. $groupid .', '.$arrStudents[$j][userid].' )';
				mysql_query($sqlassmembers);
			}
			else{
				$stdId = $j;
				break;
			}
		}
		$g = $g + 1;
	  }
	$toapply =0;
	$courseid =0;
	$arrStudents = null;
}

   mysql_close($con);
?>			


<html>
<head>
<title>Horizon Academy Management</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<meta name="keywords" content="keywords here">
<meta name="description" content="description here">
<meta name="author" content="Mohammed Belyamani">
<meta name="publisher" content="interspire.com">
<meta name="robots" content="index, follow"> <!-- (robot commands: all, none, index, no index, follow, no follow) -->
<meta name="revisit-after" content="30 days">
<meta name="distribution" content="global"> 
<meta name="rating" content="general">
<meta name="content-language" content="english">
<script type="text/javascript">

function getStudents() {
  document.getElementById('courseid').value = document.getElementById('courseSelect').value;
  document.getElementById('agaform').submit();
}

function apply() {
  document.getElementById('toapply').value = 1;
  var groupsize = document.getElementById('groupsize').value;
  if (groupsize==null || groupsize == "" ){
	alert("You need to set the group size");
  }
  else{
	document.getElementById('groupsizevalue').value = groupsize;
	document.getElementById('agaform').submit();
  }
}

function cancel() {
  document.getElementById('courseid').value = 0;
  document.getElementById('toapply').value = 0;
  document.getElementById('agaform').submit();
}

function exit()
{
    window.location.href='index.php';
}
//-->
</script>
<link href="style.css" rel="stylesheet" type="text/css">
</head>

<body style="margin:0;">
<table width="747" border="0" align="center" cellpadding="0" cellspacing="0">
  <tr>
    <td><img src="images/spacer.gif" width=747 height=11 alt=""></td>
  </tr>
  
  <tr>
    <td><img src="images/spacer.gif" width=747 height=11 alt=""></td>
  </tr>
  <tr>
    <td><table width="100%" border="0" cellpadding="0" cellspacing="0">
      <tr>
        <td valign="top" background="images/pixi_lightgrey.gif"><table border=0 cellpadding=0 cellspacing=0 bgcolor="#ffffff">
          <tr bgcolor="#ffffff">
            <td colspan=3><!-- #BeginEditable "mainpic" --><img src="images/logotip.jpg" width=250 height=125 alt=""><!-- #EndEditable --></td>
          </tr>
          <tr> </tr>
          
        </table></td>
        <td valign="top" background="images/pixi_lightgrey.gif"><table width="516" border=0 cellpadding=0 cellspacing=0>
          <tr>
            <td rowspan=2><img src="images/spacer.gif" width=0 height=250 alt=""></td>
            <td height="30" background="images/pixi_headergrey.gif" align="center"> <h1><img src="images/spacer.gif" width=450 height=10 alt=""><br />
<br />Horizon Academy Management</h1><br /></td>
          </tr>
		<tr> 
		  <td colspan="2">
			<input type="Button" id="AGAmenu" name="AGAmenu" value="A.G.A" onclick="to_aga();" disabled>
			<input type="Button" id="Feauture2menu" name="Feauture2menu" value="Email/role" onclick="to_aga();">
			<input type="Button" id="Feauture3menu" name="Feauture3menu" value="Report/Classes" onclick="to_aga();">
			<input type="Button" id="Feauture4menu" name="Feauture4menu" value="Dashboard" onclick="to_aga();">
		  </td> 
		</tr> 

<tr><td colspan="2">		  
<form method="post" id="agaform" name="agaform" action="features.php">  
	
	<table> 	  
		<tr> 
		  <td colspan="2"><h4>Automatic Groups Assignment</h4></td> 
		</tr> 
		<tr> 
		  <td style="padding-bottom: 0px;" valign="top">
			<b>Courses:<b><br />
			<select id="courseSelect" >
				<?php
					$count = count($arrCourse);
					for ($j = 0; $j < $count; $j++) {
				?>
				<option value="<?php 
							echo $arrCourse[$j][courseid].'"';
							if ($arrCourse[$j][courseid] == $courseid){
								echo "selected";
							}
							echo "> ";
							echo $arrCourse[$j][coursename];?></option>
				<?php } ?>
			</select>
		  </td>
		  <td style="padding-bottom: 0px;" valign="top">
			
			<?php $studentCount = count($arrStudents);?>
			<b>List of students:<b><?php echo $studentCount; ?><br />
			<select width="120" size="<?php if ($studentCount>20) echo 20; else echo $studentCount; ?>" disabled>
				<?php
					if ($studentCount==0)
					{
					echo '<option>No Students</option>';
					} else{									
						for ($j = 0; $j < $studentCount; $j++) {
				?>
				<option value="<?php echo $arrStudents[$j][lastname].$j;?>"><?php echo $arrStudents[$j][lastname].' '.$arrStudents[$j][firstname];?></option>
				<?php } }?>
			</select> 
		  </td>
		</tr>
		<tr> 
		  <td style="padding-bottom: 0px;" valign="top">
		  </td>
		  <td style="padding-bottom: 0px;" valign="top">
			<input type="button" value="Refresh" onclick="getStudents();">
		  </td>
		</tr>
		<tr> 
		  <td colspan="2"> 
			  Group size: <select id="groupsize">
							  <option value=""></option>
							  <option value="10">10</option>
							  <option value="11">11</option>
							  <option value="12">12</option>
							  <option value="14">14</option>
							  <option value="15">15</option>
							  <option value="16">16</option>
							  <option value="17">17</option>
							  <option value="18">18</option>
							  <option value="19">19</option>
							  <option value="20">20</option>
							  <option value="21">21</option>
							  <option value="22">22</option>
							  <option value="23">23</option>
							  <option value="24">24</option>
							  <option value="25">25</option>
							  <option value="26">26</option>
							  <option value="27">27</option>
							  <option value="28">28</option>
							  <option value="29">29</option>
							  <option value="30">30</option>
							</select>
		  </td> 
		</tr> 
		<tr> 
		  <td colspan="2"> 
			  <input type="button" value="Apply"	onclick=apply() />
			  <input type="button" value="Cancel" 	onclick=cancel() />
			  <input type="button" value="Close" 	onclick=exit() />
		  </td> 
		</tr> 
	</table>

	 <input type="hidden" id="username" name="username" value="<?php echo $username;?>"/>
	 <input type="hidden" id="password" name="password" value="<?php echo $pwd;?>"/>
	 <input type="hidden" id="courseid" name="courseid" value="<?php echo $courseid;?>" />
	 <input type="hidden" id="groupsizevalue" name="groupsizevalue" value="<?php echo $groupsizevalue;?>" />
	 <input type="hidden" id="toapply" name="toapply" value="<?php echo 0;?>" />
	 
</form>  
			</td>
          </tr>
		 
        </table></td>
      </tr>
    </table></td>
  </tr>
  <tr>
    <td><table width="747" border=0 cellpadding=0 cellspacing=0>
  <tr>
    <td width="15" align="left" valign="top" background="images/pixi_grey.gif"> <img src="images/basecurve_left.jpg" width=15 height=38 alt=""></td>
    <td background="images/pixi_grey.gif"> <img src="images/spacer.gif" width=218 height=1 alt=""></td>
    <td width="522" valign="top" background="images/pixi_grey.gif"><img src="images/spacer.gif" alt="" width=522 height=13 hspace="0" vspace="0"><br>
        <span class="baseline">Copyright 2011 Horizon Academy Institute</span></td>
    <td width="14" align="right" valign="top" background="images/pixi_grey.gif"><img src="images/basecurve_right.jpg" width=11 height=38 alt=""></td>
  </tr>
</table></td>
  </tr>
  <tr>
    <td><img src="images/spacer.gif" width=747 height=11 alt=""></td>

  </tr>
</table>


<script src="form-validation.js"></script> 

</body>

</html>
